package com.api.volunteer.websocket;

import com.alibaba.fastjson.JSONObject;
import com.api.volunteer.model.MessageRecord;
import com.api.volunteer.service.VolunteerActivitesService;
import com.api.volunteer.websocket.model.Message;
import com.google.gson.JsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author 邹宇杰
 * @email 2901570623@qq.com
 * @date 2022/4/4 13:27
 */
@Component
@ServerEndpoint("/api/message/{openid}")
public class WebSocketServer {


    static VolunteerActivitesService volunteerActivitesService;

    @Autowired
    public void setVolunteerActivitesService(VolunteerActivitesService volunteerActivitesService){
        WebSocketServer.volunteerActivitesService = volunteerActivitesService;
    }

    private Session session;

    /**
     * 接收者的openid
     */
    public String openid;

    @OnOpen
    public void onOpen(Session session,@PathParam("openid") String openid) {
        this.session = session;
        this.openid=openid;
        if(WebSocketConfig.map.containsKey(openid)){
            // 当用户进入小程序咨询时, 如果有以前的webscoket连接则删除, 重新创建
            WebSocketConfig.map.remove(openid);

            WebSocketConfig.map.put(openid,this);
        }else{

            WebSocketConfig.map.put(openid,this);
            //在线数加1
            WebSocketConfig.connectNumbers.getAndAdd(1);
        }
    }

    /**
     * 收到客户端消息后调用的方法
     * @param message
     * 客户端发送过来的消息
     **/
    @OnMessage
    public void onMessage(String message, Session session) {

        //可以群发消息
        //消息保存到数据库、redis
        if(!message.isEmpty()){
            try {
                //解析发送的报文
                System.out.println(message);
                Message msg = JSONObject.parseObject(message, Message.class);
                //追加发送人(防止串改)
                msg.setOpenid(this.openid);
                String toOpenid = msg.getToOpenid();
                //传送给对应toUserId用户的websocket
                if(!toOpenid.isEmpty() && WebSocketConfig.map.containsKey(toOpenid)){

                    volunteerActivitesService.saveMessageRecord(msg.getVolunteerId(), msg.getOpenid(), msg.getToOpenid(), msg.getMsg());

                    List<MessageRecord> messageRecords = volunteerActivitesService.listMessage(msg.getVolunteerId(), msg.getOpenid(), msg.getToOpenid());

                    this.session.getBasicRemote().sendText(JSONObject.toJSONString(messageRecords));

                    WebSocketConfig.map.get(toOpenid).session.getBasicRemote().sendText(JSONObject.toJSONString(messageRecords));
                }else{
                    System.out.println("该用户不存在");

                }
            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

}
